package com.zhugang.week13.binarysearch;

/**
 * @program algorithms
 * @description: BinarySearchByCycleArrayMin
 * @author: chanzhugang
 * @create: 2022/11/25 20:16
 */
public class BinarySearchByCycleArrayMin {

    /**
     * 循环有序数组中找最小值，  比较难(画图举例才能理解)
     * [7,9,10,11,15,1,2,3,5,6]
     *
     * @param a
     * @param n
     * @return
     */
    public int bsearch(int[] a, int n) {
        int low = 0;
        int high = n - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;

            if (low == high) {
                // 唯一一个特殊的地方
                return mid;
            }

            // 先处理命中，后处理不命中
            if (mid != 0 && (a[mid] < a[mid - 1]) || (mid == 0 && a[mid] < a[high])) {
                // 5 6 1 2 3   || 1 2 3 4 5
                return mid;
            } else if (a[mid] > a[high]) {
                // 右侧循环有序
                // 4 5 6 1 2 3
                low = mid + 1;
            } else {
                // 左侧循环有序 或者 左侧有序

                high = mid - 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        BinarySearchByCycleArrayMin binarySearchByCycleArrayMin = new BinarySearchByCycleArrayMin();
        int[] a = {7, 9, 10, 11, 15, 1, 2, 3, 5, 6};
        int minIndex = binarySearchByCycleArrayMin.bsearch(a, a.length);
        System.out.println(minIndex);

    }
}